<?php

namespace  App\Http\Controllers\V1;

use App\Events\V1\UserCountChannelEvent;
use App\Events\V1\UserRegEvent;
use App\Helpers\RestResponseFactory;
use App\Helpers\RestUtils;
use App\Helpers\Utils;
use App\Http\Controllers\Controller;
use App\Models\Factory\ComDeviceFactory;
use App\Models\Factory\SmsFactory;
use App\Models\Factory\UserFactory;
use App\Models\Factory\UserInviteCodeFactory;
use App\Models\Orm\User;
use Illuminate\Http\Request;


/**
 * 快捷登录
 * Class QuickController
 * @package App\Http\Controllers\V1
 */
class QuickController extends  Controller
{

    /**
     * 快速登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function QuickLogin(Request $request)
    {
        //接收参数
        $data = $request->input();

//        检查验证码是否正确
        $re = SmsFactory::getSmsRandomFromCache($data['userphone'].'_code');
        if (!($re == $data['code']))
        {
            return RestResponseFactory::ok(RestUtils::getStdObj(), RestUtils::getErrorMessage(1204), 1204);
        }

        //生成该用户的唯一标识token并保存到数据库
        $user = UserFactory::getUserByMobile($data['userphone']);
        //重复验证短信验证码只记录一次
        if(empty($user['token']))
        {
            $channel_h5 = $request->input('channel');
            if(isset($data['terminal']) && $data['terminal'] == 1){

                $channel['nid'] = isset($channel_h5) ? $channel_h5 : 'weixin1';
            }else{
                $channel['nid'] = $request->header('channel') ? : 'weixin1';
            }


            // 统计注册人次
            $channel['type'] = 2;
            $channel['userphone'] = $data['userphone'];
            //统计用户渠道
            event(new UserCountChannelEvent($channel));
        }




//		//根据用户的主键生成token
        $token['token'] = md5("anwen".time().$user['id']);
//		//把用户的唯一标识保存到数据库内
        UserFactory::addUserTokenByMobile($data['userphone'],$token);

//        $token['token']  = UserFactory::getUserByMobile($data['userphone'])->token;
        //更新用户的最后登录时间
        UserFactory::addUserLassTime($data['userphone']);


        $channel['nid'] = $request->header('channel') ? : 'weixin1';
        $channel['userphone'] = $data['userphone'];



        return RestResponseFactory::ok($token);
    }
}
